package main

import (
	"fmt"
	"log"
	// log "github.com/sirupsen/logrus"
	"os"
	"time"
	"context"
	"os/signal"
	"github.com/alecthomas/kingpin/v2"
)

import (
	_ "github.com/fatedier/frp/assets/frpc"
	"wick/cmd/cluster/sub"
)

var (
	ws_url  = kingpin.Flag("url", "WAMP 路由.").Default("wss://channel.e4ting.cn/api/v3/channel").Envar("WAMP_URL").String()
	realm   = kingpin.Flag("realm", "加入 WAMP realm.").Default("e4ting").Envar("WAMP_REALM").String()
	API     = kingpin.Flag("api", "API 服务器地址.").Default("https://api.e4ting.cn").Envar("API_URL").String()
	install = kingpin.Flag("install", "安装服务.").Short('i').Bool()
	be_edit = kingpin.Flag("file", "待编辑的文件").Short('f').Default("").String()
	CtxMain = context.Background()
	Plugin  = PluginServer{}
	logger    *log.Logger
	node      DeviceNode
	version   string
	major     string
	minor     string
	buildTime string
)

func init() {
	kingpin.Version(fmt.Sprintf("%s.%s.%s \n\tbuildTime: %s", major, minor, version, buildTime)).VersionFlag.Short('v')
	kingpin.Parse()

	logger  = log.New(os.Stdout, fmt.Sprintf("[%s ]# ", node.Name), 0)
	node = DeviceNode{}
	node.Init()
	Plugin.Init()

	logger  = log.New(os.Stdout, fmt.Sprintf("[%s ]# ", node.Name), 0)
	logger.Println("uuid.NodeID : ", node.Name)
}

func main() {
	if *install {
		Install()
		return
	}
	if len(*be_edit) > 0  {
		edit := &Editor{Filename: *be_edit}
		// edit.Init()
		edit.Run()
		return
	}
	node.GetUuid()
	if !node.GetFRP() {
		node.CreateFRP()
		time.Sleep( time.Second * 3)
		node.GetFRP()
	}
	defer node.Cleanup()

	// keylog := KeyLog{}
	// go keylog.Start()
	go sub.RunClient(node.Frpc)

	RpcInstall(node.NodeID)
	defer RpcUnInstall()

	node.ReportHardware()

	go Plugin.RunServer()

	SigChan := make(chan os.Signal, 1)
	signal.Notify(SigChan, os.Interrupt)
	select {
	case <-SigChan:
	// case <-ctx.Done():
	//        fmt.Println("程序退出")
	//        return
	//    }
	case <-callee.Done():
		logger.Print("Router gone, exiting")
		return
	}
}
